import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const search = searchParams.get('search')
    const status = searchParams.get('status')
    
    const whereClause: any = {}
    
    if (search) {
      whereClause.OR = [
        { projectTitle: { contains: search } },
        { name: { contains: search } },
        { projectCode: { contains: search } },
        { description: { contains: search } }
      ]
    }
    
    if (status && status !== 'all') {
      whereClause.level1 = status
    }
    
    const projects = await db.researchProject.findMany({
      where: whereClause,
      include: {
        creator: {
          select: {
            id: true,
            name: true,
            email: true
          }
        },
        versions: {
          include: {
            creator: {
              select: {
                name: true,
                email: true
              }
            }
          },
          orderBy: {
            createdAt: 'desc'
          }
        },
        histories: {
          include: {
            user: {
              select: {
                name: true,
                email: true
              }
            }
          },
          orderBy: {
            createdAt: 'desc'
          }
        }
      },
      orderBy: {
        createTime: 'desc'
      }
    })
    
    return NextResponse.json(projects)
  } catch (error) {
    console.error('Error fetching research projects:', error)
    return NextResponse.json(
      { error: 'Failed to fetch research projects' },
      { status: 500 }
    )
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    
    const {
      projectTitle,
      name,
      projectCode,
      projectType,
      category,
      applicationType,
      description,
      customerName,
      applicantName,
      projectManagerName,
      priority,
      startDate,
      endDate,
      deadline,
      planStartDate,
      planEndDate,
      createdBy,
      
      // 技术规格参数
      voltage,
      current,
      frequency,
      power,
      efficiency,
      
      // 电机控制参数
      motorSpeed,
      motorTorque,
      controlMode,
      motorType,
      motorPower,
      motorVoltage,
      motorCurrent,
      motorPoles,
      motorPhases,
      
      // 控制模式参数
      controlAlgorithm,
      communicationProtocol,
      
      // PWM控制参数
      pwmStartupDutyCycle,
      pwmShutdownDutyCycle,
      pwmDutyCycleRange,
      pwmFrequencyRange,
      pwmResolution,
      
      // 保护参数体系
      stallProtection,
      overvoltageProtection,
      undervoltageProtection,
      overcurrentProtection,
      overtemperatureProtection,
      undertemperatureProtection,
      shortCircuitProtection,
      reversePolarityProtection,
      
      // 保护子参数
      stallThreshold,
      stallTimeout,
      overvoltageThreshold,
      undervoltageThreshold,
      overcurrentThreshold,
      overtemperatureThreshold,
      undertemperatureThreshold,
      shortCircuitThreshold,
      temperatureSensorType,
      temperatureHysteresis,
      currentLimit,
      voltageLimit,
      protectionRecoveryTime,
      protectionRetryCount,
      
      // 硬件特性参数
      certification,
      lowPowerMode,
      hallSensor,
      fgSignal,
      brakeFunction,
      encoderSupport,
      thermalManagement,
      emcCompliance,
      ipRating,
      coolingMethod,
      
      // 性能参数
      speedControlAccuracy,
      torqueControlAccuracy,
      dynamicResponse,
      efficiencyRating,
      noiseLevel,
      rippleCurrent,
      
      // 实用工具参数
      motorCalculator,
      speedCalculation,
      loadCharacteristic,
      inertiaCalculation,
      
      // 硬件相关参数
      mcuType,
      memorySize,
      interfaceType,
      powerRequirements,
      operatingTemp,
      storageTemp,
      humidity,
      vibration,
      shock,
      
      // 软件相关参数
      architecture,
      stackSize,
      heapSize,
      programmingLanguage,
      developmentEnv,
      targetPlatform,
      osRequirements,
      
      // 性能参数
      processingTime,
      dataRate,
      performanceEfficiency,
      responseTime,
      throughput,
      accuracy,
      reliability,
      
      // 测试参数
      testCases,
      passRate,
      testDuration,
      testMethods,
      testStandards,
      qualityStandards,
      
      // 法规认证
      safetyStandard,
      emcStandard,
      environmentalStandard,
      certifications,
      standards,
      regulatoryBody,
      
      // 成本预算
      estimatedCost,
      budgetLimit,
      currency,
      
      // 供应链信息
      supplierLeadTime,
      supplierList,
      keyComponents,
      suppliers,
      leadTime,
      
      // 风险评估
      technicalRiskLevel,
      scheduleRiskLevel,
      budgetRiskLevel,
      technicalRisks,
      scheduleRisks,
      budgetRisks,
      mitigationPlans
    } = body
    
    const project = await db.researchProject.create({
      data: {
        projectTitle,
        name,
        projectCode,
        projectType,
        category,
        applicationType,
        description,
        customerName,
        applicantName,
        projectManagerName,
        priority,
        startDate: startDate ? new Date(startDate) : null,
        endDate: endDate ? new Date(endDate) : null,
        deadline: deadline ? new Date(deadline) : null,
        planStartDate: planStartDate ? new Date(planStartDate) : null,
        planEndDate: planEndDate ? new Date(planEndDate) : null,
        level1: 'DRAFT',
        level2: '草稿阶段',
        statusDesc: '项目已创建，待完善信息',
        createdBy,
        createTime: new Date(),
        
        // 技术规格参数
        voltage,
        current,
        frequency,
        power,
        efficiency,
        
        // 电机控制参数
        motorSpeed,
        motorTorque,
        controlMode,
        motorType,
        motorPower,
        motorVoltage,
        motorCurrent,
        motorPoles,
        motorPhases,
        
        // 控制模式参数
        controlAlgorithm,
        communicationProtocol,
        
        // PWM控制参数
        pwmStartupDutyCycle,
        pwmShutdownDutyCycle,
        pwmDutyCycleRange,
        pwmFrequencyRange,
        pwmResolution,
        
        // 保护参数体系
        stallProtection,
        overvoltageProtection,
        undervoltageProtection,
        overcurrentProtection,
        overtemperatureProtection,
        undertemperatureProtection,
        shortCircuitProtection,
        reversePolarityProtection,
        
        // 保护子参数
        stallThreshold,
        stallTimeout,
        overvoltageThreshold,
        undervoltageThreshold,
        overcurrentThreshold,
        overtemperatureThreshold,
        undertemperatureThreshold,
        shortCircuitThreshold,
        temperatureSensorType,
        temperatureHysteresis,
        currentLimit,
        voltageLimit,
        protectionRecoveryTime,
        protectionRetryCount,
        
        // 硬件特性参数
        certification,
        lowPowerMode,
        hallSensor,
        fgSignal,
        brakeFunction,
        encoderSupport,
        thermalManagement,
        emcCompliance,
        ipRating,
        coolingMethod,
        
        // 性能参数
        speedControlAccuracy,
        torqueControlAccuracy,
        dynamicResponse,
        efficiencyRating,
        noiseLevel,
        rippleCurrent,
        
        // 实用工具参数
        motorCalculator,
        speedCalculation,
        loadCharacteristic,
        inertiaCalculation,
        
        // 硬件相关参数
        mcuType,
        memorySize,
        interfaceType,
        powerRequirements,
        operatingTemp,
        storageTemp,
        humidity,
        vibration,
        shock,
        
        // 软件相关参数
        architecture,
        stackSize,
        heapSize,
        programmingLanguage,
        developmentEnv,
        targetPlatform,
        osRequirements,
        
        // 性能参数
        processingTime,
        dataRate,
        performanceEfficiency,
        responseTime,
        throughput,
        accuracy,
        reliability,
        
        // 测试参数
        testCases,
        passRate,
        testDuration,
        testMethods,
        testStandards,
        qualityStandards,
        
        // 法规认证
        safetyStandard,
        emcStandard,
        environmentalStandard,
        certifications,
        standards,
        regulatoryBody,
        
        // 成本预算
        estimatedCost: estimatedCost ? parseFloat(estimatedCost) : null,
        budgetLimit: budgetLimit ? parseFloat(budgetLimit) : null,
        currency,
        
        // 供应链信息
        supplierLeadTime,
        supplierList,
        keyComponents,
        suppliers,
        leadTime,
        
        // 风险评估
        technicalRiskLevel,
        scheduleRiskLevel,
        budgetRiskLevel,
        technicalRisks,
        scheduleRisks,
        budgetRisks,
        mitigationPlans
      },
      include: {
        creator: {
          select: {
            id: true,
            name: true,
            email: true
          }
        }
      }
    })
    
    // 创建历史记录
    await db.projectHistory.create({
      data: {
        projectId: project.id,
        action: 'CREATED',
        description: '创建研究项目',
        userId: createdBy,
        toLevel1: 'DRAFT',
        toLevel2: '草稿阶段'
      }
    })
    
    return NextResponse.json(project)
  } catch (error) {
    console.error('Error creating research project:', error)
    return NextResponse.json(
      { error: 'Failed to create research project' },
      { status: 500 }
    )
  }
}